package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.OrderDetail;
import com.itheima.bean.Orders;
import com.itheima.dao.OrderDetailDao;
import com.itheima.dto.OrdersDto;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @date 2023/2/25
 */
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailDao, OrderDetail> implements OrderDetailService {
    @Autowired
    private OrdersService ordersService;
    /**
     * 订单详情分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page orderPage(Integer page, Integer pageSize) {
       //0.分页拦截器(实现)
        //1.创建一个page对象
        Page<OrderDetail> odPage = new Page<OrderDetail>(page, pageSize);
        //2.用wrapper查询结果
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<OrderDetail>();
        wrapper.orderByAsc(OrderDetail::getOrderId);
        //封装结果
        this.page(odPage,wrapper);
        return odPage;
    }

    @Override
    public Page<OrdersDto> getOrders(Integer page, Integer pageSize, String number, Date beginTime, Date endTime) {
        Page<Orders> ordersPage = ordersService.page(new Page<Orders>(page, pageSize), new LambdaQueryWrapper<Orders>()
                .like(number != null, Orders::getNumber, number)
                .between(beginTime != null, Orders::getOrderTime, beginTime, endTime));
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        List<OrdersDto> ordersDtos = ordersPage.getRecords().stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtos.forEach(ordersDto -> {
            ordersDto.setOrderDetails(this.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId,ordersDto.getId())));
        });
        ordersDtoPage.setRecords(ordersDtos);
        return ordersDtoPage;
    }

    /**
     * 查询订单状态
     * @param page
     * @param pageSize
     * @param beginTime
     * @param endTime
     * @return
     */
//    @Override
//    public Orders state(Integer page, Integer pageSize, Date beginTime, Date endTime) {
//
//        return null;
//    }
}
